package com.cloud.rou.im.client.msg;

import com.cloud.rou.im.core.base.ResultVO;
import com.cloud.rou.im.msg.Msg;

import java.util.concurrent.*;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
public class ChatMsgDeliveredQueueExecutor {

    private Msg msg;

    private MsgResponsePool pool = MsgResponsePool.getInstance();

    private WorkListener listener;

    public ChatMsgDeliveredQueueExecutor(WorkListener listener) {
        this.listener = listener;
    }

    public ChatMsgDeliveredQueueExecutor() {
    }

    public void addListener(WorkListener listener) {
        this.listener = listener;
    }

    class SubWork implements Callable<ResultVO> {
        @Override
        public ResultVO call() throws Exception {
            for (; ; ) {
                ResultVO resultVO = pool.get(msg.getMsgId());
                if (resultVO != null) {
                    return resultVO;
                }
            }
        }
    }

    public void start(Msg msg) {
        this.msg = msg;
        FutureTask<ResultVO> task = new FutureTask<>(new SubWork());

        new Thread(task).start();
        try {
            ResultVO resultVO = task.get(10, TimeUnit.SECONDS);
            if (listener != null) {
                listener.listen(resultVO);
            }
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            ResultVO fail = ResultVO.fail(msg.getMsgId());
            if (listener != null) {
                listener.listen(fail);
            }
        }
    }


}

